<?php
/**
 * Front Controller
 * 
 * @author Sean Crystal <seancrystal@gmail.com>
 * @package MutantVole
 */
require_once 'components/Settings.php';
require_once 'components/exceptions/Exceptions.php';
require_once 'components/Dispatch.php';
require_once 'PHPUnit/Framework.php';
require_once 'constants.php';

// JSON-RPC POST
if (preg_match('/json/', $_SERVER['HTTP_ACCEPT'])) {
	$_REQUEST['json-rpc'] = $HTTP_RAW_POST_DATA;
}

session_start();

$settings = Settings::LoadSettingsFile(SETTINGS_FILE);

try {
	Dispatch::Init($_REQUEST, $settings);
} catch (PageNotFoundException $e) {
	Dispatch::Redirect($settings['404Page']);
}

define('TEMPLATE_PREFIX', APP_DIR ."/". Dispatch::$mod ."/templates/". Dispatch::$page);

$app = new Application($settings);

// figure out the name of the class declared in the page file
$classes1 = get_declared_classes();
require Dispatch::$pageFile;
$classes2 = get_declared_classes();
Dispatch::$pageClass = end(array_diff($classes2, $classes1));

// Start the app
$app->Go(Dispatch::GetPage(), Dispatch::GetRequest());


function __autoload($class) {
	if (preg_match('/Presenter$/', $class)) {
		$filename = COMPONENT_DIR ."/presenters/{$class}.php";
	} elseif (preg_match('/View$/', $class)) {
		$filename = COMPONENT_DIR ."/views/{$class}.php";
	} elseif (preg_match('/Renderer$/', $class)) {
		$filename = COMPONENT_DIR ."/renderers/{$class}.php";
	} elseif (preg_match('/^i/', $class)) {
		$filename = ROOT_DIR ."/interfaces/{$class}.php"; 
	} elseif (preg_match('/^JSONRPC/', $class)) {
	    $filename = COMPONENT_DIR ."/jsonrpc/{$class}.php";
	} elseif (preg_match('/Pagelet$/', $class)) {
	    $filename = PAGELET_DIR ."/{$class}.php";
	}
	
	if (file_exists($filename)) {
		require_once $filename;
	} elseif (file_exists(COMPONENT_DIR ."/{$class}.php")) {
		require_once COMPONENT_DIR ."/{$class}.php";
	}
}

?>
